/**
 * TODO: Using Promise to reconstructing this
 * @class
 * @param { object } _store save published functions
 */
class IcyObserver {
  constructor() {

    // event line
    this._store = {};
  }

  subscribe(event, callback) {
    
    // FIXME: security?
    // push the functions with the same event name in line
    if (this._store[event] instanceof Array) {
      this._store[event].push(callback);
    } else if (!this._store[event]) {
      this._store[event] = [];
      this._store[event].push(callback);
    }
  }

  publish(event, ...args) {
    
    try {
      for (let eachCall of this._store[event]) {

        // map the saved callbacks
        eachCall(...args);
      }
      
    } catch (err) {
      console.error(`there is no event named ${event} in store. ${err}`);
      return null;
    }
  }

  list() {
    // FIXME: console out function
    console.log(`Current stored message => ${this._store}`);
  }

  cancel(event) {
    try {
      delete this._store[target];
    } catch (err) {
      console.error(`there is no ${event} in store`);
    }
  }
}


// ------ TEST ------ //
function test() {
  let icy = new IcyObserver();
  
  {
    // subscribe 1
    let b = 'b';
    icy.subscribe('right', (e) => {
      console.log(b);  // b
      b = e;
      console.log(b);  // c
    });
    icy.list();
  }
  
  {
    // subscribe 2
    let a = 'a';
    icy.subscribe('right', () => {
      console.log(a);  // a
    });
    icy.list();
  }
  
  {
    // publish
    icy.publish('right', 'c');
  }
  
  {
    // cancel
    icy.cancel('right');
    icy.publish('right'); // ReferenceError
  }  
}
// test();
// ------ TEST END ------ //

module.exports = IcyObserver;